package org.ant.gui.actionListeners;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

import javax.swing.JOptionPane;

import org.ant.ctrl.CodesManager;
import org.ant.gui.AntFrame;
import org.ant.util.Code;
import org.w3c.dom.Document;

public class SaveActionListener implements ActionListener {

	private AntFrame frame;

	public SaveActionListener() {
	}

	public void actionPerformed(ActionEvent arg0) {
		System.out.println("Save Action");
		frame = AntFrame.getInstance();
		save();
	}

	public int save() {
		int choice = 0;
		Code code = CodesManager.getInstane().getCurrentCode();
		if (code.getPath() == null) {
			return new SaveAsActionListener().saveAs();
		}
		try {
			File file = new File(code.getPath());
			if (!file.exists()) {
				file.createNewFile();
			} else {
				int confirm = JOptionPane.showConfirmDialog(frame,
						"File already exists, OVERWRITE?", "File Overwrite",
						JOptionPane.YES_NO_OPTION);
				switch (confirm) {
				case JOptionPane.YES_OPTION:
					choice = JOptionPane.YES_OPTION;
					break;// proceed

				case JOptionPane.NO_OPTION:
					return JOptionPane.NO_OPTION;// cancel

				}
			}
			saveFile(file, frame.getInputTabbedPane().getCurrentPane()
					.getText());
			code.compile();
		} catch (Exception ex) {
			JOptionPane.showMessageDialog(frame,
					"Error saving the current file", "Error",
					JOptionPane.ERROR_MESSAGE);
			ex.printStackTrace();
		}

		return choice;
	}

	public void saveFile(File file, String doc) {
		try {
			FileWriter fw = new FileWriter(file);
			fw.write(doc);
			fw.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
